(function() {
    'use strict';

    angular.module('app.uploadFile')
        .directive("vgFileSelect", ['FileReaderFactory', '$timeout', vgFileSelect])
        .directive("vgSimulateClick", ['$timeout', vgSimulateClick]);

    function vgFileSelect (FileReaderFactory, $timeout) {
        return {
            scope: {
                ngModel: '='
            },

            link: function($scope, el) {

                function getFile(file) {
                    var handler = function(result) {
                            $timeout(function() {
                                $scope.ngModel = result;
                            });
                        };

                    FileReaderFactory.readAsDataUrl(file, $scope)
                        .then(handler, handler);
                }

                el.bind("change", function(e) {
                    var file = e.target.files[0];
                    if (file) {
                        getFile(file);
                    }
                });
            }
        }
    }

    function vgSimulateClick ($timeout) {
        return {
            restrict: 'A',

            link: function (scope, iElement, iAttrs) {
                iElement.click(function(event) {
                    event.preventDefault();
                    event.stopPropagation();

                    $timeout(function() {
                        angular.element(iAttrs.vgSimulateClick).trigger('click');
                    });
                });
            }
        };
    }

})();